
class Bonus {

  // this.stop = this.state.round
  constructor(state, backCallback, turnCallback) {
    this.state = state;
    this.backCallback = backCallback;
    this.accumulateTime = 0;
    this.deltaTime = 0; // 允许小数
    this.waitForStop = true;
    this.turnCallback = turnCallback;
    //this.stop = true;
  }

  start () {
    this.state.round = true;
    this.accumulateTime = 0;
    this.deltaTime = 4;
    this.waitForStop = false;
    this.state.round = true;

    if (this.state.cursor == -1) {
      this.state.cursor = 0;
    }
    //this.stop = false;
  }

  stop () {
    this.waitForStop = true;
  }

  tick (time) {
    if (!this.state.round) {
      return;
    }

    this.accumulateTime += time;
    while (this.accumulateTime > this.deltaTime) {
      this.step()
      this.accumulateTime -= this.deltaTime;
    }
  }

  step () {
    let cursor = this.state.cursor;

    if (this.waitForStop) {
      if (this.deltaTime >= 40) {
        if (this.state.frames[cursor].enable) {
          // 停下来了
          this.accumulateTime = 0;
          this.deltaTime = 0;
          this.waitForStop = true;
          this.state.round = false;
          this.backCallback();
        } else {
          // 继续翻一格
          this.turnPage();
        }
      } else if (this.deltaTime >= 32) {
        if (this.state.frames[cursor].enable) {
          // 减速翻一格
          this.turnPage();
          this.deltaTime *= (1 + Math.random() * 0.2);
        } else {
          // 继续翻一格
          this.turnPage();
        }
      } else {
        // 减速翻一格
        this.turnPage();
        this.deltaTime *= (1 + Math.random() * 0.2);
      }
    } else {
      // 继续翻一格
      this.turnPage();
    }

  }

  turnPage () {
    const frameLen = this.state.frames.length;
    this.state.cursor = (this.state.cursor + 1) % frameLen;
    if (this.turnCallback) {
      this.turnCallback();
    }
  }
}


export {
	Bonus
};

